package com.tim.soundseechina;

import java.util.Map;

import org.apache.log4j.Logger;

import com.tim.soundseechina.entity.InformationInfo;

public class Landscape extends Thread {
	private static Logger log = Logger.getLogger(Landscape.class);
	private static final String MODEL_NAME = "scenery/";

	@Override
	public void run() {
		// 风景相册
		String albumUrl = SoundSeeChina.URL + "/cn/scenery_album.aspx";
		Cache cache = (Cache) SoundSeeChina.factory.getBean("cache");

		// 获取检索条件
		Map<Short, Integer> provinceMap = cache.getProvinceMap();
		Map<String, Integer> queryMap = cache.getQueryMap();
		for (Short province : provinceMap.keySet()) {
			for (String query : queryMap.keySet()) {
				InformationInfo info = new InformationInfo();
				// 风景类型
				info.setMenuId(1);
				info.setTypeId(provinceMap.get(province));
				info.setSubTypeStr(queryMap.get(query) + ",");
				String url = albumUrl + "?a=" + province + "&t=" + query
						+ "&st=1";
				log.warn("begin: " + url);
				String content = getConent(url);
				if (content != null) {
					// 获取风景信息
					getPagerInfo(info, content, cache);
					// 获取分页地址
					String pagerStr = getPagerString(content);
					// 有分页操作
					if (pagerStr != null) {
						// 获取分页相关信息
						String pagerNo = pagerStr.substring(pagerStr
								.lastIndexOf(",'") + 2, pagerStr
								.lastIndexOf("'"));
						// 第二页起抓
						for (int i = 1; i < Integer.parseInt(pagerNo); i++) {
							getPagerInfo(
									info,
									getConent(url
											+ "&__EVENTTARGET=ctl00$contentMaster$AspNetPager1&__EVENTARGUMENT="
											+ (i + 1)), cache);
						}
					}
					log.warn("end: " + url);
				}else {
					log.warn("null: " + url);
				}
			}
		}
		log.warn("风景相册已全部抓取完毕...........");
	}

	public static void getPagerInfo(InformationInfo info, String content,
			Cache cache) {
		String temp = StringUtil.getStringFromPattern(content, "(.*)</table>");
		String[] tempArr = temp.split("<div class=\"alb-alb\">");
		for (int i = 0; i < tempArr.length; i++) {
			InformationInfo dataInfo = new InformationInfo();
			// 获取信息页面地址
			String infoUrl = StringUtil.getStringFromPattern(tempArr[i],
					"<a href='(.*)'>");
			// 中文信息页url
			String url = SoundSeeChina.URL + "/cn/" + infoUrl;
			// 获取中文信息
			String tempInfo = getInformationTemp(dataInfo, url);
			// 获取标题
			String title = getInformationTitle(tempInfo);
			String cnSubTypeStr = info.getSubTypeStr();
			String enSubTypeStr = cache.getCn2EnId(Integer
					.parseInt(cnSubTypeStr.substring(0, cnSubTypeStr
							.indexOf(","))))
					+ ",";
			// 获取数据库信息
			if (cache.getInformation(title) != null) {
				dataInfo = cache.getInformation(title);
				// 未抓过
				if (dataInfo.getSubTypeStr().indexOf("," + cnSubTypeStr) == -1) {
					// 修改信息类型
					dataInfo.setSubTypeStr(dataInfo.getSubTypeStr()
							+ cnSubTypeStr);
					// 更新数据库
					SoundSeeChina.informationInfoService.update(dataInfo);
				}
			} else {// 未抓过-数据入库
				// 设置类型
				dataInfo.setMenuId(info.getMenuId());
				dataInfo.setTypeId(info.getTypeId());
				dataInfo.setSubTypeStr("," + cnSubTypeStr);
				// 设置中文类型
				dataInfo.setLanType("cn");
				dataInfo.setStatus((short) 0);
				// 设置标题
				dataInfo.setTitle(title);
				// 抓取设置内容
				dataInfo.setInformationDesc(getInformationContent(tempInfo));
				// 抓取图片列表
				dataInfo.setImgSrc(getImgListInfo(infoUrl));
				// 获取首个图片地址
				String indexImgStr = StringUtil.getStringFromPattern(
						tempArr[i], "<img src='..(.*)' alt");
				String fileType = indexImgStr.substring(indexImgStr
						.lastIndexOf("."));
				// 图片保存路径
				String imgFile = MODEL_NAME + System.currentTimeMillis()
						+ fileType;
				// 下载图片
				HttpClientProc.getUrl2File(SoundSeeChina.URL + indexImgStr,
						SoundSeeChina.CHINESE_CULTURE + imgFile);
				// 设置首页图片路径
				dataInfo.setIndexImg(imgFile);
				// 中文数据入库
				SoundSeeChina.informationInfoService.create(dataInfo);
			}

			// 英文信息
			InformationInfo enInfo = new InformationInfo();
			// 英文信息页url
			url = SoundSeeChina.URL + "/en/" + infoUrl;
			tempInfo = getInformationTemp(enInfo, url);
			// 获取标题
			title = getInformationTitle(tempInfo);
			if (cache.getInformation(title) != null) {// 已经存在的信息
				enInfo = cache.getInformation(title);
				// 未抓过
				if (enInfo.getSubTypeStr().indexOf("," + enSubTypeStr) == -1) {
					// 修改信息类型
					enInfo.setSubTypeStr(enInfo.getSubTypeStr() + enSubTypeStr);
					// 更新数据库
					SoundSeeChina.informationInfoService.update(enInfo);
				}
			} else {// 未抓过-数据入库
				// 设置图片连接
				enInfo.setImgSrc(dataInfo.getImgSrc());
				enInfo.setMenuId(dataInfo.getMenuId());
				// 转换为英文ID
				enInfo.setTypeId(cache.getCn2EnId(dataInfo.getTypeId()));
				enInfo.setSubTypeStr("," + enSubTypeStr);
				enInfo.setStatus(dataInfo.getStatus());
				enInfo.setIndexImg(dataInfo.getIndexImg());
				enInfo.setLanType("en");
				enInfo.setTitle(title);
				// 抓取设置内容
				enInfo.setInformationDesc(getInformationContent(tempInfo));
				// 英文数据入库
				SoundSeeChina.informationInfoService.create(enInfo);
			}
		}
	}

	public static String getCnStr2EnStr(String cnStr) {
		StringBuilder enStr = new StringBuilder();
		String[] tempArr = cnStr.split(",");
		for (int i = 1; i < tempArr.length - 1; i++) {

		}
		return enStr.toString();
	}

	public static String getInformationTemp(InformationInfo info, String url) {
		// 设置来源页
		info.setFromLink(url);
		// 获取页面信息
		String tempStr = HttpClientProc.getUrl2String(url,
				SoundSeeChina.CHAR_SET);
		return StringUtil
				.getStringFromPattern(tempStr,
						"id=\"three-con-right-top\">(.*)<div class=\"four-ethnic-bottom-top\">");
	}

	// 获取图片列表信息
	@SuppressWarnings("static-access")
	public static String getImgListInfo(String url) {
		// 获取页面编号
		String pageNo = url.substring(url.lastIndexOf("_") + 1, url
				.lastIndexOf("."));
		url = SoundSeeChina.URL + "/cn/scenery/cultureimages.ashx?Name="
				+ pageNo;
		// 获取页面信息
		String tempStr = HttpClientProc.getUrl2String(url,
				SoundSeeChina.CHAR_SET);
		if (tempStr == null || "".equals(tempStr)) {
			return null;
		} else {
			StringBuilder imgPathStr = new StringBuilder();
			String[] tempStrArr = tempStr.split("</li><li");
			for (int i = 0; i < tempStrArr.length; i++) {
				String imgUrl = StringUtil.getStringFromPattern(tempStrArr[i],
						"src=\"../..(.*)\" alt=.*");
				String fileType = imgUrl.substring(imgUrl.lastIndexOf("."));
				String imgFile = MODEL_NAME + System.currentTimeMillis()
						+ fileType;
				// 下载图片
				HttpClientProc.getUrl2File(SoundSeeChina.URL + imgUrl,
						SoundSeeChina.CHINESE_CULTURE + imgFile);
				try {
					Thread.currentThread().sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if (i != 0) {
					imgPathStr.append(",");
				}
				imgPathStr.append(imgFile);
			}
			return imgPathStr.toString();
		}
	}

	// 获取资讯标题
	public static String getInformationTitle(String content) {
		return StringUtil
				.getStringFromPattern(
						content,
						"<span style=\"color: #0183fd; font-size: 14px; font-weight: bold;\">(.*)</span><br />");
	}

	// 获取资讯内容
	public static String getInformationContent(String content) {
		String temp = StringUtil.getStringFromPattern(content, "<p>(.*)</p>");
		if (temp == null) {
			temp = StringUtil
					.getStringFromPattern(content,
							"(<font face=\"Verdana\" color=\"#808080\" size=\"2\">.*)</p>");
		}
		return temp;
	}

	public static String getConent(String url) {
		String content = HttpClientProc.getUrl2String(url,
				SoundSeeChina.CHAR_SET);
		try {
			content = StringUtil
					.getStringFromPattern(content,
							"<div class=\"alb-alb\">(.*)<!-- AspNetPager V7.0 for VS2008 End -->");
		} catch (Exception e) {
			content = null;
		}
		return content;
	}

	public static String getPagerString(String content) {
		return StringUtil.getStringFromPattern(content,
				"class=\"paginator\">(.*)</div>");
	}
}
